import { formatDate, isArray } from "@/utils";
import { Button, Divider, Image, Space, type TableColumnProps } from "@arco-design/web-react";
import {
	Link,
	type RegisteredRouter,
	type ToPathOption,
} from "@tanstack/react-router";
import StColumnButton, { isButtonVisible } from "./column-button.tsx";
import type { StColumnType, StRenderFunction } from "./types.ts";

export function renderColumn<TModel>(
	stColumn: StColumnType<TModel>,
): TableColumnProps<TModel> {
	const column = { ...stColumn } as TableColumnProps<TModel>;
	if (!column.render) {
		switch (stColumn.type) {
			case "no":
				column.render = (_, __, index) => index + 1;
				column.align = stColumn.align || "center";
				column.width =
					!stColumn.width || stColumn.width < 60 ? 60 : stColumn.width;
				break;
			case "date":
				column.render = (value) => formatDate(value, stColumn.dateFormat);
				column.align = stColumn.align || "center";
				break;
			case "img": {
				const imgWidth = stColumn.imgWidth || stColumn.imgSize || 32;
				const imgHeight = stColumn.imgHeight || stColumn.imgSize || 32;
				column.render = (value) =>
					value && <Image src={value} width={imgWidth} height={imgHeight} />;
				break;
			}
			case "link":
				column.render = (_, record) =>
					stColumn.click && (
						<Link
							to={(
								stColumn.click as StRenderFunction<
									TModel,
									ToPathOption<RegisteredRouter>
								>
							)(record)}
						/>
					);
				break;
			case "button":
				column.render = (value, record) => (
					<Button type={"text"} onClick={() => stColumn.click?.(record)}>
						{value}
					</Button>
				);
				break;
		}
	}
	if (stColumn.sort) {
		column.sorter = true;
	}
	if (stColumn.buttons && isArray(stColumn.buttons)) {
		column.align = stColumn.align || "center";
		column.render = (_, record) => {
			if (!stColumn.buttons) return null;

			const buttons = stColumn.buttons
				.filter((options) => isButtonVisible(record, options))
				.map((options, index) => (
					<StColumnButton
						key={index.toString()}
						record={record}
						options={options}
					/>
				));

			return <Space split={<Divider type={"vertical"} />}>{buttons}</Space>;
		};
	}
	return column;
}
